package com.wjx.happensbefore.monitorlock;

import com.wjx.happensbefore.Utils;

import java.util.concurrent.locks.ReentrantLock;

/**
 * All Lock implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock, as described in The Java Language Specification (17.4 Memory Model) :
 * A successful lock operation has the same memory synchronization effects as a successful Lock action.
 * A successful unlock operation has the same memory synchronization effects as a successful Unlock action.
 * @see java.util.concurrent.locks.Lock
 */
public class MonitorLockRuleReentrantLock {
    private static boolean stop = false;

    private static ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args) {
        Thread updater = new Thread(new Runnable() {
            @Override
            public void run() {
                Utils.sleep(1000);
                reentrantLock.lock();
                try {
                    stop = true;
                    System.out.println("updater set stop true.");
                } finally {
                    reentrantLock.unlock();
                }
            }
        }, "updater");

        Thread getter = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    reentrantLock.lock();
                    try {
                        if (stop){
                            System.out.println("getter stopped.");
                            break;
                        }
                    }finally {
                        reentrantLock.unlock();
                    }
                }
            }
        }, "getter");
        updater.start();
        getter.start();
    }

}
